import Vue from 'vue'
import Vuex from 'vuex'
import {
  setUserInfo, getUserInfo, removeUserInfo, getToken,
  setToken, removeToken
} from '@/utils/auth'
import { LoginService, GetUserInfoService } from '@/api/user'
Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    token: getToken() || '',
    userInfo: getUserInfo()
  },
  mutations: {
    setToken (state, token) {
      state.token = token
      setToken(token)
    },
    removeToken (state) {
      state.token = null
      removeToken()
    },
    setUserInfo (state, userInfo) {
      state.userInfo = userInfo
      setUserInfo(userInfo)
    },
    removeUserInfo (state) {
      state.userInfo = null
      removeUserInfo()
    }
  },
  getters: {},
  actions: {
    async login (context, value) {
      try {
        // 调用登录接口
        const { token } = await LoginService(value)
        context.commit('setToken', token)
      } catch (error) {
        console.error('登录失败:', error.message)
        throw error // 继续向上抛出错误，供组件捕获
      }
    },
    async getUserInfo (context) {
      const res = await GetUserInfoService()
      context.commit('setUserInfo', res)
      return res
    },
    // 退出登录
    async LoginOut (commit) {
      commit('removeToken')
      commit('setUserInfo', {})
    }
  }
})
export default store
